from typing import Optional, List

from sqlmodel import Field, SQLModel, Relationship

from .base import IdType,SQLBaseModel


class BaseApi(SQLModel):
    name: str = Field(index=True, description="接口名称")
    auth_key: Optional[str] = Field(default=None, index=True, description="权限字符")
    label: Optional[str] = Field(default=None, index=True, description="接口注释标签")
    path: Optional[str] = Field(default=None, description="接口地址")
    http_method: Optional[str] = Field(default=None, index=True, description="接口方法")
    description: Optional[str] = Field(default=None, description="描述")
    sort: int = Field(default=100, index=True, description="排序")
    is_enabled: bool = Field(default=True, index=True, description="是否启用")


class Api(SQLBaseModel, BaseApi, table=True):
    __tablename__ = "api"

    """一对多自引用关系"""
    parent_id: Optional[IdType] = Field(
        default=None, index=True, foreign_key="api.id", description="上级ID"
    )
    # 系统使用假删除，所有不需要级联删除，后续自己处理删除逻辑
    """
    选项	描述
        save-update	自动将新对象添加到会话中
        merge	级联合并操作
        expunge	级联清除操作
        delete	级联删除操作
        delete-orphan	删除不再与父对象关联的子对象
        all	等同于 save-update, merge, expunge, delete
        none	禁用所有级联
    """
    children: List["Api"] = Relationship(
        back_populates="parent",
        sa_relationship_kwargs={"cascade": "save-update, merge","lazy": "raise"},
    )
    # 对于自引用关系，需要使用 sa_relationship_kwargs={"remote_side": [id]} 来指定关系的"远程端"
    parent: Optional["Api"] = Relationship(
        back_populates="children", sa_relationship_kwargs={"remote_side": "Api.id"}
    )
